//
//  ZODPreviewController.m
//  ZTEOnlineDoc
//
//  Created by 万伟琦 on 2018/9/10.
//  Copyright © 2018年 万伟琦. All rights reserved.
//

#import "ZODPreviewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "ZTEOnlineDoc.h"
#import "NSBundle+OnlineRead.h"
#import "ZODPreviewController+JSHandle.h"
#import "NSBundle+OnlineRead.h"
#import "ZODCacheManager.h"
#import "ZODGlobalStorage.h"
#import "ZODAttInfo.h"
#import "ZODCommonDefine.h"
#import "NSFileManager+ZOD.h"
#import "ZODWatermarkView.h"


#define ZOD_SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define ZOD_SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

@interface ZODPreviewController ()

@property (nonatomic, copy) NSString *fileName;
@property (nonatomic, assign) CGFloat navHeight;


@end

@implementation ZODPreviewController


- (instancetype)initWithConfiguration:(ZODOnlineDocConfiguration *)config attInfo:(ZODAttInfo *)attInfo {
    self = [super init];
    if (self) {
        _attInfo = attInfo;
        _configuration = config;
        _authResult = ZODAuthResultTimeout;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    if (!self.navigationController.navigationBar.isHidden) {
        self.navigationController.navigationBar.hidden = YES;
    }
    
    self.group = dispatch_group_create();
    self.queue = dispatch_queue_create("onlineRead.sdk.authQueue", DISPATCH_QUEUE_SERIAL);
    
    [self setupUI];
    
    [self checkAuth];
}

- (void)checkAuth {
    
    NSString *attID;
    if (!self.attInfo.RID || self.attInfo.RID.length < 10) {
        attID = self.attInfo.ID;
    }else {
        attID = self.attInfo.RID;
    }
    
    NSURL *indexURL = [NSDefaultFileManager getDocCacheIndexFileURLByDocMD5:attID];
    NSData *data = [NSData dataWithContentsOfURL:indexURL];
    NSDictionary *indexDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:NULL];
    if (indexDict) {
        self.authResult = [[indexDict objectForKey:@"authRes"] integerValue];
    }else {
        //调用鉴权接口
        __weak typeof(self) wself = self;
        [self authRequestWithCompletion:^(ZODAuthResult result) {
            wself.authResult = result;
            [ZODSharedCacheManager cacheAuthResult:[NSString stringWithFormat:@"%ld", result]];
        }];
    }
    
}

- (void)setupUI {
    [self setupNavBar];
    [self setupWebview];
    [self setupWaterView];
}

- (void)setupNavBar {
    
    CGFloat navHeight;
    if ([UIScreen mainScreen].bounds.size.height >= 812) {
        navHeight = 88;
    }else {
        navHeight = 64;
    }
    self.navHeight = navHeight;
    UIView *navBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ZOD_SCREEN_WIDTH, navHeight)];
    navBar.backgroundColor = [UIColor colorWithRed:241/255.0 green:241/255.0 blue:241/255.0 alpha:1];
    
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, navHeight - 40, ZOD_SCREEN_WIDTH - 50, 40)];
    NSBundle *zodBundle = [NSBundle onLineRead_Bundle];
    UIImage *res = [UIImage imageNamed:@"closebtn.png" inBundle:zodBundle compatibleWithTraitCollection:nil];
    [backBtn setImage:res forState:UIControlStateNormal];
    [backBtn setTitle:self.attInfo.N forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor colorWithRed:31/255.0 green:121/255.0 blue:238/255.0 alpha:1] forState:UIControlStateNormal];
    [backBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [backBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [navBar addSubview:backBtn];
    
    [self.view addSubview:navBar];
}

- (void)setupWaterView {
    ZODWatermarkView *waterView = [[ZODWatermarkView alloc] initWithFrame:CGRectMake(0, self.navHeight, ZOD_SCREEN_WIDTH, ZOD_SCREEN_HEIGHT) markTitle:self.configuration.waterText markFont:nil markColor:nil respond:NO];
    [self.view addSubview:waterView];
}

#pragma mark - WebView Configuration
- (void)setupWebview {
    WKWebViewConfiguration *configuration = [self webViewJSInteractionDependencyConfiguration];
    
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, self.navHeight, ZOD_SCREEN_WIDTH, ZOD_SCREEN_HEIGHT - self.navHeight) configuration:configuration];
    [self.view addSubview:webView];
    
    //配置 webView 加载 html
    [self addDataSourceForWebView:webView];
    
    //添加代理
    [self addDelegatesForWebView:webView];
    
    self.webView = webView;
}

- (void)addDelegatesForWebView:(WKWebView *)webView {
    webView.navigationDelegate = (id<WKNavigationDelegate>)self;
}

- (void)addDataSourceForWebView:(WKWebView *)webView {
    NSString *htmlResource = [self loadResourceByDocTypeWithDocName:self.attInfo.N];
    NSString *htmlResourcePath = [NSString stringWithFormat:@"SDKView/%@", htmlResource];
    NSURL *url = [[NSBundle onLineRead_Bundle] URLForResource:htmlResourcePath withExtension:nil];
    NSString *urlStr = [NSString stringWithFormat:@"%@?lang=%ld&platform=2&debug=%ld&eventId=123", [url absoluteString], self.configuration.lang, self.configuration.opMode];
    NSURL *urlWithParam = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:urlWithParam];
    [webView loadRequest:request];
}

- (NSString *)loadResourceByDocTypeWithDocName:(NSString *)docName {
    
    NSString *defaultHtml = @"default.html";
    NSString *excelHtml = @"excel.html";
    NSString *txtHtml = @"txt.html";
    NSString *imgHtml = @"img.html";
    
    NSDictionary *map = @{
                          @"xls":   excelHtml,
                          @"xlsx":  excelHtml,
                          @"csv":   excelHtml,
                          @"txt":   txtHtml,
                          @"jpg":   imgHtml,
                          @"jpeg":  imgHtml,
                          @"gif":   imgHtml,
                          @"png":   imgHtml,
                          @"bmp":   imgHtml,
                          @"tiff":  imgHtml,
                          @"exif":  imgHtml,
                          @"svg":   imgHtml,
                          @"heic":  imgHtml,
                          };
    NSString *docType = docName.pathExtension;
    NSString *htmlType = [map objectForKey:docType];
    
    return htmlType?:defaultHtml;
}

#pragma mark 返回按钮事件
- (void)back {
    
    [ZODSharedCacheManager writeMemoryCacheToDiskWithCompletion:^{
        
        //按照时间逆序，从最久远的开始删除
        [ZODSharedCacheManager clearFileCachesByRule];
        
    }];

    
    if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)dealloc {
    self.webView.navigationDelegate = nil;
}

@end
